<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use GuzzleHttp\Client;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Request;
/**
 * 2020-02-08
 * 这是从coupons获取数据判断每天接口新数据
 */
class Coupons extends Command
{
    protected $signature = 'coupons';
    protected $description = 'conpons数据源判断每天新进的卡券数量';
    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $this->info('*********************program start***********************');
        
        //定义参数对接口数据进行请求
        $base_url='http://rss.coupons.com/xmlserve.asp?go=13903xh2010&bid=1051650001';

        $client=new Client();
        $response = $client->request('GET',$base_url);
        $res_data=$response->getBody()->read(120000000);

        //mongo驱动定义
        $manager = new \MongoDB\Driver\Manager("mongodb://localhost:27017");
        
        //当接口有返回数据时候，对数据库中数据进行查询 去重复数据后入口
        if($res_data){
            //查库参数
            $filter = [];
            $options = [
                'projection' => [
                    'couponid' => 1,
                    '_id'=>0
                ]
            ];

            // 查询数据
            $query = new \MongoDB\Driver\Query($filter, $options);
            $cursor = $manager->executeQuery('local.coupons', $query);
            
            $ids=[];
            foreach ($cursor as $key => $value) {
                $value=(array)$value;
                $ids[]=$value['couponid'];
            }

            //接口数据进行处理
            $objectXml = simplexml_load_string($res_data);

            foreach ($objectXml->item as $key => $value) {
                $value=(array)$value;
                if(!in_array($value['couponid'],$ids)){
                    $to_save_coupons[]=[
                        'couponid'=>$value['couponid'],
                        'link'=>$value['link'],
                        'description'=>$value['description'],
                        'expiration'=>$value['expiration'],
                        'create_time'=>date('Y-m-d')
                    ];
                }else{
                    $to_save_coupons=[];
                }
            }
        }else{  
            $this->error('接口无数据总数返回');
        }

        //将数据保存到mongodb中
        if($to_save_coupons){
            $bulk = new \MongoDB\Driver\BulkWrite;

            foreach ($to_save_coupons as $key => $value) {
                $bulk->insert($value); 
            }
            $result=$manager->executeBulkWrite('local.coupons', $bulk);
            $this->line('Running:'.date('Y-m-d h:m:s').json_encode($result));
        }else{
            $this->line('Running:'.date('Y-m-d h:m:s').' 未发现可处理的新数据');
        }

        $this->info('**********************program stop***********************');
    }
}
